package com.ivy.wechatforclient.utils;

import android.support.annotation.Nullable;

import com.ivy.wechatforclient.entity.User;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Lenovo on 2017/11/20.
 */

public class HttpUtil {

    @Nullable
    public static String getByHttpConn(String path , String opreation){
        try {
            //提交数据到服务器
            //拼装路径
            /*String path = "http://192.168.49.36:8080/WeChatForServer/UserServlet"
                    +"?username=" + URLEncoder.encode(user.getUsername(),"UTF-8")
                    + "&password=" + URLEncoder.encode(user.getPassword(),"UTF-8")
                    + "&opreation=login";*/


            URL url = new URL(path + "?" + opreation);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接

            conn.setRequestMethod("GET");//设置请求方式为get

            conn.setConnectTimeout(5000);//设置连接超时时间为5秒

            int code = conn.getResponseCode();//获得请求码
            if(code == 200){
                InputStream is = conn.getInputStream();
                String text = StreamTools.readInputStream(is);
                return text;
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String postByHttpConn(String path , Map<String,String> params , String opreation){
        try {
            //提交数据到服务器
            //拼装路径

            URL url = new URL(path);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接

            conn.setRequestMethod("POST");//设置请求方式为get

            conn.setConnectTimeout(5000);//设置连接超时时间为5秒
            //准备数据
             /* String data = "username="+ URLEncoder.encode(user.getUsername(),"UTF-8")
                    + "&password=" + URLEncoder.encode(user.getPassword(),"UTF-8")
                    + "&opreation = login";*/


            String data = null;
            for (Map.Entry<String,String>  entry: params.entrySet()) {
                data += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(),"UTF-8") + "&";
            }
            data = "opreation =" + opreation;

            //指定要提交的数据实体
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", data.length()+"");

            //post的方式实际上是浏览器把数据写给了服务器
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(data.getBytes());

            int code = conn.getResponseCode();//获得请求码
            if(code == 200){
                InputStream is = conn.getInputStream();
                String text = StreamTools.readInputStream(is);
                return text;
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 采用httpclient get提交数据
     */
    public static String getByHttpClient(String path , String opreation){
        try {
            //1.打开一个浏览器
            HttpClient client = new DefaultHttpClient();
            //2.输入地址

            HttpGet httpGet = new HttpGet(path + "?" + opreation);
            //3.敲回车
            HttpResponse response = client.execute(httpGet);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                InputStream is = response.getEntity().getContent();
                String text = StreamTools.readInputStream(is);
                return text;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 采用httpclient post提交数据
     * @return
     */
    public static String postByHttpClient(String path , Map<String,String> params , String opreation){
        try {
            //1.打开一个浏览器
            HttpClient client = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(path);

            //指定要提交的数据实体
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for (Map.Entry<String,String>  entry: params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(),entry.getValue());
                parameters.add(pair);
            }
            parameters.add(new BasicNameValuePair("opreation", opreation));

            httpPost.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
            //3.敲回车
            HttpResponse response = client.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                InputStream is = response.getEntity().getContent();
                String text = StreamTools.readInputStream(is);
                return text;
                //return EntityUtils.toString(response.getEntity());
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static JSONObject getJSONByURL(String path , String opreation) throws  Exception{
        return new JSONObject(getByHttpClient(path , opreation));
    }

    public static JSONArray getJSONArrayByURL(String path , String opreation) throws  Exception{
        return new JSONArray(getByHttpClient(path , opreation));
    }
    public static JSONArray postJSONArrayByURL(String path , Map<String,String> params ,  String opreation) throws  Exception{

        return new JSONArray( postByHttpClient (path ,params, opreation));
    }
}
